package cn.bandeqing.base.aliyun;

import com.aliyun.sts20150401.Client;
import com.aliyun.sts20150401.models.AssumeRoleRequest;
import com.aliyun.sts20150401.models.AssumeRoleResponse;
import com.aliyun.sts20150401.models.AssumeRoleResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.SneakyThrows;
import org.dromara.hutool.core.date.DatePattern;
import org.dromara.hutool.core.date.DateTime;
import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.json.JSONUtil;

public class StsToken {

    static Config config = new com.aliyun.teaopenapi.models.Config()
            .setAccessKeyId("LTAI5tGjAgXnMjgzAb28rqsv")
            .setAccessKeySecret("YGERrwlAIbUV09A4Yrmk9JYERYFIui")
            .setEndpoint("sts.cn-shenzhen.aliyuncs.com");

    static Client client;

    // 最近一次获取时间
    static DateTime timeout;

    static {
        try {
            client = new Client(config);
        } catch (Exception e) {
            throw new RuntimeException("client = new com.aliyun.sts20150401.Client(config)");
        }
    }

    private static AssumeRoleResponseBody.AssumeRoleResponseBodyCredentials credentials;

    @SneakyThrows
    public static void init() {
        AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest()
                .setRoleArn("acs:ram::1533201055094086:role/ramoss")
                .setRoleSessionName("bdqcloudosssession");
        RuntimeOptions runtime = new RuntimeOptions();
        AssumeRoleResponse assumeRoleResponse = client.assumeRoleWithOptions(assumeRoleRequest, runtime);
        System.out.println(JSONUtil.toJsonStr(assumeRoleResponse));
        credentials = assumeRoleResponse.getBody().getCredentials();
        timeout = DateUtil.parse(credentials.getExpiration(), DatePattern.UTC_FORMAT);
    }

    public static AssumeRoleResponseBody.AssumeRoleResponseBodyCredentials get() {
        if (credentials == null || timeout.getTime() + 10 * 60 * 1000L <= System.currentTimeMillis()) {
            // 初始化 或则10分钟后过期
            init();
        }
        return credentials;
    }

}
